package cn.ix.spring.security.config;

import cn.ix.spring.security.bean.TokenAuthenticateFilter;
import cn.ix.spring.security.handler.CustomAuthenticationEntryPoint;
import cn.ix.spring.security.handler.MyAccessDeniedHandler;
import cn.ix.spring.security.service.impl.CustomUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 *
 */
@Configuration
@EnableWebSecurity
// 开启注解权限验证
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private TokenAuthenticateFilter tokenAuthenticateFilter;

    @Autowired
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement()
                // 设置 session 为无状态，因为基于 token 不需要 session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .sessionFixation().none()
                .and()
                .authorizeRequests()
                .antMatchers("/account/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                //用户无权限访问链接，给出友好提示
                .accessDeniedHandler(myAccessDeniedHandler)
                // 未登录返回403
                .authenticationEntryPoint(customAuthenticationEntryPoint)
                .and()
                .csrf().disable()
                .addFilterBefore(tokenAuthenticateFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
